<template>
  <!-- <div style="height: 100vh;width: 100vw"> -->
  <el-container>
    <el-main>
      <div ref="viewport" class="viewport">
        <!-- tabindex allows for div to be focused -->
        <!-- <div ref="display" class="display" tabindex="0"/> -->
        <div ref="display" class="display"/>
      </div>
    </el-main>
  </el-container>
  <!-- </div> -->
</template>

<script>
import Guacamole from 'guacamole-common-js'
import GuacMouse from '@/libs/GuacMouse'
import states from '@/libs/states'
import clipboard from '@/libs/clipboard'
// import axios from 'axios'

Guacamole.Mouse = GuacMouse.mouse

function serialize (obj) {
  let str = [];
  for (const p in obj)
    if (obj[p]) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}
export default {
  name:'GuacClient3',
  data() {
    return {
      demo:'win',
      connected: false,
      display: null,
      currentAdjustedHeight: null,
      client: null,
      keyboard: null,
      mouse: null,
      lastEvent: null,
      connectionState: states.IDLE,
      errorMessage: '',
      arguments: {},
      query:{
          // guacad_addr:'guacd.mojotv.cn:4822',
          guacad_addr:'127.0.0.1:4822',
          asset_protocol:'rdp',
          asset_host:'wangjing.cec.cc',
          asset_port:'3389',
          asset_user:'wangjing@cec.cc',
          asset_password:'cec-123456wj@',
          screen_width:2512,
          screen_height:1318,
          screen_dpi:128,
          GatewayHostname: "ccg.cec.cc",
          GatewayPort: "88",
          GatewayUsername: "wangjing@cec.cc",
          GatewayPassword: "cec-123456wj@",
      },

      Successdialog: true,//控制弹出
      Sencond: "认证成功",//设置初始倒计时
      isDisabled: true,
      isMobile: false,
    }
  },
 
  computed: {

    wsUrl() {
      let loc = window.location, new_uri;
      if (loc.protocol === "https:") {
        new_uri = "wss:";
      } else {
        new_uri = "ws:";
      }
      //new_uri += "//127.0.0.1:9528"
      new_uri += "//" + loc.host;
      new_uri += "/ws";
      return `${new_uri}`
    }
  },
  watch: {
    connectionState(state) {
      this.$notify({
        title: state,
        type: 'success'
      });
    }
  },
  methods: {
    sendMsg () {
      window.close()
    },

    getSencond () {
      const that = this
      const interval = window.setInterval(function () {
        // --that.Sencond
        if (that.Sencond === "正在登录") {
          that.Successdialog = false
          window.clearInterval(interval)
          // this.$refs.display.click();
          //that.sendMsg()//倒计时结束时运行的业务逻辑，这里的是关闭当前页面
        }
      }, 1000)
    },
    atChangeDemo(v){
      if (v === 'win'){
        this.query = {
          guacad_addr:'guacd.mojotv.cn:4822',
          asset_protocol:'rdp',
          asset_host:'wangjing.cec.cc',
          asset_port:'3389',
          asset_user:'wangjing@cec.cc',
          asset_password:'cec-123456wj@',
          screen_width:1024,
          screen_height:768,
          screen_dpi:128,
          GatewayHostname: "ccg.cec.cc",
          GatewayPort: "88",
          GatewayUsername: "wangjing@cec.cc",
          GatewayPassword: "cec-123456wj@",
        }
        return
      }
      if (v === 'vnc'){
        this.query = {
          guacad_addr:'guacd.mojotv.cn:4822',
          asset_protocol:'vnc',
          asset_host:'guacd-vnc.mojotv.cn',
          asset_port:'5901',
          asset_user:'root',
          asset_password:'vncpassword',
          screen_width:1024,
          screen_height:768,
          screen_dpi:128,
          GatewayHostname: "",
          GatewayPort: "",
          GatewayUsername: "",
          GatewayPassword: "",
        }
        return
      }
      if (v === 'rdp'){
        this.query = {
          guacad_addr:'guacd.mojotv.cn:4822',
          asset_protocol:'rdp',
          asset_host:'wangjing.cec.cc',
          asset_port:'3389',
          asset_user:'wangjing@cec.cc',
          asset_password:'cec-123456wj@',
          screen_width:1024,
          screen_height:768,
          screen_dpi:128,
          GatewayHostname: "ccg.cec.cc",
          GatewayPort: "88",
          GatewayUsername: "wangjing@cec.cc",
          GatewayPassword: "cec-123456wj@",

        }
      }
    },
    doGuacdConnect(){
      this._setScreenSize()
      this.startGuacamole()
    },
    send(cmd) {
      if (!this.client) {
        return
      }
      for (const c of cmd.data) {
        this.client.sendKeyEvent(1, c.charCodeAt(0))
      }
    },
    copy(cmd) {
      if (!this.client) {
        return
      }
      clipboard.cache = {
        type: 'text/plain',
        data: cmd.data
      }
      clipboard.setRemoteClipboard(this.client)
    },
    handleMouseState(mouseState) {
      const scaledMouseState = Object.assign({}, mouseState, {
        x: mouseState.x / this.display.getScale(),
        y: mouseState.y / this.display.getScale(),
      })
      this.client.sendMouseState(scaledMouseState);
    },
    _setScreenSize(){
      const elm = this.$refs.viewport
      if (!elm || !elm.offsetWidth) {
        // resize is being called on the hidden window
        return
      }
      // let pixelDensity = window.devicePixelRatio || 1
      // const width = elm.clientWidth * pixelDensity
      // const height = elm.clientHeight * pixelDensity
      // this.query.screen_height = height - 20
      // this.query.screen_width = width - 20
      let pixelDensity = window.devicePixelRatio || 1
      this.query.screen_width = Math.ceil(elm.clientWidth * 1.33333) 
      this.query.screen_height = Math.ceil(elm.clientHeight * 1.33333)
      console.log(this.query.screen_width)
      console.log(this.query.screen_height)
      console.log(pixelDensity)
    },
    resize() {
      const elm = this.$refs.viewport
      if (!elm || !elm.offsetWidth) {
        // resize is being called on the hidden window
        return
      }

      let pixelDensity = window.devicePixelRatio || 1
      const width = elm.clientWidth * pixelDensity
      const height = elm.clientHeight * pixelDensity
      if (this.display.getWidth() !== width || this.display.getHeight() !== height) {
        this.client.sendSize(width, height)
      }
      // setting timeout so display has time to get the correct size
      setTimeout(() => {
        const scale = Math.min(
            elm.clientWidth / Math.max(this.display.getWidth(), 1),
            elm.clientHeight / Math.max(this.display.getHeight(), 1)
        )
        this.display.scale(scale)
      }, 100)
    },
    startGuacamole() {
      // GuacadAddr    string `form:"guacad_addr"`
      // AssetProtocol string `form:"asset_protocol"`
      // AssetHost     string `form:"asset_host"`
      // AssetPort     string `form:"asset_port"`
      // AssetUser     string `form:"asset_user"`
      // AssetPassword string `form:"asset_password"`
      // ScreenWidth   int    `form:"screen_width"`
      // ScreenHeight  int    `form:"screen_height"`
      // ScreenDpi     int    `form:"screen_dpi"`

      let tunnel = new Guacamole.WebSocketTunnel(this.wsUrl)


      if (this.client) {
        this.display.scale(0)
        this.uninstallKeyboard()
      }

      this.client = new Guacamole.Client(tunnel);
      clipboard.install(this.client)

      tunnel.onerror = status => {
        // eslint-disable-next-line no-console
        console.error(`Tunnel failed ${JSON.stringify(status)}`)
        this.connectionState = states.TUNNEL_ERROR
      }

      tunnel.onstatechange = state => {
        switch (state) {
            // Connection is being established
          case Guacamole.Tunnel.State.CONNECTING:
            this.connectionState = states.CONNECTING
            this.Sencond = "正在连接"
            break;

            // Connection is established / no longer unstable
          case Guacamole.Tunnel.State.OPEN:
            this.connectionState = states.CONNECTED
            break;

            // Connection is established but misbehaving
          case Guacamole.Tunnel.State.UNSTABLE:
            // TODO
              this.$message.error("不稳定")
            break;

            // Connection has closed
          case Guacamole.Tunnel.State.CLOSED:
            this.connectionState = states.DISCONNECTED
            // 添加页面返回,清空user_uuid
            sessionStorage.removeItem("user_uuid")
            this.$router.go(-1)
            break;
        }
      }

      this.client.onstatechange = clientState => {
        switch (clientState) {
          case 0:
            this.connectionState = states.IDLE
            break
          case 1:
            // connecting ignored for some reason?
            break
          case 2:
            this.connectionState = states.WAITING
            break
          case 3:
            this.connectionState = states.CONNECTED
            window.addEventListener('resize', this.resize)
            this.$refs.viewport.addEventListener('mouseenter', this.resize)

            clipboard.setRemoteClipboard(this.client)
            // 立即显示画面
            this.Sencond = "正在登录"
            // 

            // eslint-disable-next-line no-fallthrough
          case 4:
          case 5:
            // disconnected, disconnecting
            break
        }
      }

      this.client.onerror = error => {
        this.client.disconnect()
        // eslint-disable-next-line no-console
        this.$message.error(`Client error ${JSON.stringify(error)}`)
        this.errorMessage = error.message
        this.connectionState = states.CLIENT_ERROR
      }

      this.client.onsync = () => {
      }

      // Test for argument mutability whenever an argument value is received
      this.client.onargv = (stream, mimetype, name) => {
        if (mimetype !== 'text/plain')
          return;

        const reader = new Guacamole.StringReader(stream);

        // Assemble received data into a single string
        let value = '';
        reader.ontext = text => {
          value += text;
        };

        // Test mutability once stream is finished, storing the current value for the argument only if it is mutable
        reader.onend = () => {
          const stream = this.client.createArgumentValueStream('text/plain', name)
          stream.onack = status => {
            if (status.isError()) {
              // ignore reject
              return
            }
            this.arguments[name] = value
          }
        };
      }

      this.client.onclipboard = clipboard.onClipboard
      this.display = this.client.getDisplay()
      const displayElm = this.$refs.display
      displayElm.appendChild(this.display.getElement());
      displayElm.addEventListener('contextmenu', e => {
        e.stopPropagation();
        if (e.preventDefault) {
          e.preventDefault();
        }
        e.returnValue = false;
      })

      let param = serialize(this.query)
      this.client.connect(param);
      window.onunload = () => this.client.disconnect();

      this.mouse = new Guacamole.Mouse(displayElm);
      // Hide software cursor when mouse leaves display
      this.mouse.onmouseout = () => {
        if (!this.display) return;
        this.display.showCursor(false);
      }
      //添加自动显示
      displayElm.focus();
      // allows focusing on the display div so that keyboard doesn't always go to session
      displayElm.onclick = () => {
        displayElm.focus()
      }
      displayElm.onfocus = () => {
        displayElm.className = 'focus'
      }
      displayElm.onblur = () => {
        displayElm.className = ''
      }

      this.keyboard = new Guacamole.Keyboard(displayElm);
      this.installKeyboard()
      this.mouse.onmousedown = this.mouse.onmouseup = this.mouse.onmousemove = this.handleMouseState
      setTimeout(() => {
        this.resize()
        displayElm.focus()
      }, 1000); // $nextTick wasn't enough
    },
    installKeyboard() {
      this.keyboard.onkeydown = keysym => {
        this.client.sendKeyEvent(1, keysym);
      };
      this.keyboard.onkeyup = keysym => {
        this.client.sendKeyEvent(0, keysym);
      };
    },
    uninstallKeyboard() {
      this.keyboard.onkeydown = this.keyboard.onkeyup = () => {
      }
    },

    objToParams(obj) {
        let arr = [];
        for (let key in obj) {
            arr.push(`${key}=${obj[key]}`);
        }
            return arr.join('&');
        },

    checkMobile() {
      this.isMobile = window.innerWidth <= 767;
      console.log(this.isMobile)    
      },
  },
  mounted() {
     window.addEventListener('resize', this.checkMobile);
     this.checkMobile(); //初始化时进行判断是否是移动设备
    //  if(this.isMobile){
    //   this.Successdialog = false
    //  }
     let user_uuid= sessionStorage.getItem('user_uuid')
     let manager_server= sessionStorage.getItem('manager_server')
     this.query.manager_server = manager_server
     console.log(user_uuid)
     this.query.user_uuid = user_uuid
     axios({
                url: "/api/getrdpinfo",
                method: "post",
                headers: {
                    'Content-Type':'application/x-www-form-urlencoded',
                },
                data: this.objToParams({"user_uuid": user_uuid, "manager_server": manager_server})
            }).then(response => {
                    console.log(response)
                    console.log(response.data.status)
                    if(response.data.status){
                        this.$message({
                        message: '获取信息成功',
                        type: 'success'
                      });
                      console.log(response.data.Data)
                    }
                    else{
                      this.$message({
                        message: '获取信息失败',
                        type: 'fail'
                      });
                    }
                }
            ).catch(error => {
                    console.log(456)
                    console.log(error)
                }
            );

     this._setScreenSize()
     this.startGuacamole()
     //this.getSencond()
  },

  beforeUnmount() {
    window.removeEventListener('resize', this.checkMobile);
    },
}
</script>

<style scoped>
.el-container{
  width: 100vw;
  height: 100vh;
  padding: 0px;
  margin: -8px;
}
.el-main{
 
  padding: 0px;
  margin: 0px;
}
.display {
  /* overflow: hidden; */
  width: 100%;
  height: 100%;
}

.viewport {
  background-color: rgba(38,92,178,1);
  background-image:  url('~@/assets/2.png');
  background-size:cover;
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0px;
}
 ::v-deep .el-dialog {
  background: rgba(0, 0, 0, 0);
    -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0);
    opacity: 0.9;
  width: 18%;
}

</style>
